package com.xzq.erp.controller;

import com.xzq.erp.ai.history.RedisChatHistory;
import com.xzq.erp.ai.vo.MessageHistoryVO;
import com.xzq.erp.ai.vo.MessageVO;
import com.xzq.erp.aspect.ApiOperationLog;
import com.xzq.erp.constants.PromptConstants;
import com.xzq.erp.context.BaseContext;
import com.xzq.erp.utils.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Arrays;
import java.util.List;

import java.util.Map;
import java.util.Objects;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai/")
@Tag(name = "智能助手相关接口")
@Slf4j
public class AiController {

    private final ChatClient chatClient;

    private final RedisChatHistory redisChatHistory;

    private final ChatMemory chatMemory;

//    private final String CHAT_MEMORY_CONVERSATION_ID_KEY = "chat_memory_conversation_id";

    /**
     * openApi 阿里千问模型 流式聊天
     * @param prompt 用户输入的提示词
     * @return Flux<String> 流式响应
     */
    @GetMapping(value = "/chat", produces = "text/html;charset=utf-8")
    @Operation(summary = "流式聊天")
    @ApiOperationLog(description = "流式聊天")
    public Flux<String> streamMultimodalChat(@RequestParam("prompt") String prompt,@RequestParam("chatId") String chatId) {
        log.info("收到聊天请求: {}", prompt);
        //  保存用户的会话ID
        redisChatHistory.save(BaseContext.getUserId(),chatId);
          return chatClient.prompt()
                    .user(prompt)
                    .advisors( a -> a.param(ChatMemory.CONVERSATION_ID,chatId)) // 保存会话记忆
                    .toolContext(Map.of("userId",BaseContext.getUserId()))
                    .stream()
                    .content();
    }

    /**
     * 获取当前用户的会话ID列表
     * @return
     */
    @GetMapping("/history")
    @Operation(summary = "获取当前用户的会话ID列表")
    @ApiOperationLog(description = "获取当前用户的会话ID列表")
     public Response<List<MessageHistoryVO>> getHistory() {
        return Response.success(redisChatHistory.getChatIds(BaseContext.getUserId()));
    }

    /**
     * 查询用户的历史会话列表
     */
    @GetMapping("/chat/{chatId}")
    @Operation(summary = "查询用户历史会话")
    @ApiOperationLog(description = "查询用户历史会话")
    public Response<List<MessageVO>> getChatHistory(@PathVariable String chatId) {
        log.info("查询用户历史会话: {}", chatId);
        List<Message> messages = chatMemory.get(chatId);
        if(Objects.isNull(messages) ||  messages.isEmpty()){
            return Response.success(Arrays.asList(new MessageVO(new SystemMessage(PromptConstants.USER_DEFAULT_PROMPT))));
        }
        return Response.success(messages.stream().map(MessageVO::new).toList());
    }

     @DeleteMapping("clear-history/{chatId}")
     @Operation(summary = "清除历史会话")
     @ApiOperationLog(description = "清除历史会话")
     public Response<Void> clearHistory(@PathVariable String chatId) {
        log.info("清除历史会话: {}", chatId);
        chatMemory.clear(chatId);
        redisChatHistory.delete(BaseContext.getUserId(),chatId);
        return Response.success();
    }
}
